package com.gemme.gemme.wode;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.gemme.gemme.BaseActivity;
import com.gemme.gemme.R;
import com.gemme.gemme.login.Constant;
import com.gemme.gemme.login.GlideCircleTransform;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.manager.DataPares;
import com.gemme.gemme.util.StrUtil;
import com.gemme.gemme.view.OnChangeLIstener;
import com.gemme.gemme.view.Product2SIngleView;
import com.gemme.gemme.view.RefreshView;
import com.gemme.gemme.view.RoundCheckBox;
import com.gemme.gemme.view.Topview;
import com.gemme.gemme.view.TuijianBean;
import com.jaeger.library.StatusBarUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

//侧滑删除地址
public class Recode2Activity extends BaseActivity{

    ArrayList<Product2SIngleView> viewList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recode);
        initView();
        initTop();
        initData();
    }



    RefreshView refreshView;
    RoundCheckBox rb_bianjia;
    View rl_edit;
    Recode2Adapter recode2Adapter;
    boolean isAll = false;
    TextView tv_delete;
    private void initView() {
       /* RecyclerView rvResult = findViewById(R.id.rvResult);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        rvResult.setLayoutManager(mLayoutManager);
        rvResult.setAdapter(new RecodeAdapter());*/
        refreshView = findViewById(R.id.refreshView);
        refreshView.setLayoutManager(new LinearLayoutManager(mContext));



        rb_bianjia = findViewById(R.id.rb_bianjia);
        rl_edit = findViewById(R.id.rl_edit);


        tv_delete = findViewById(R.id.tv_delete);
        rb_bianjia.setOnChangeLIstener(new OnChangeLIstener() {
            @Override
            public void onChangeLIstener() {
                isAll = rb_bianjia.isChecked();
                recode2Adapter.notifyDataSetChanged();
            }
        });

        tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                delteData();
            }
        });
    }

    private void delteData() {
        try {

            String ids = "";
            ArrayList<FindRecordBean2> data = recode2Adapter.getData();
            for (int i = 0; i < data.size(); i++) {
                FindRecordBean2 bean = data.get(i);
                List<FindRecordBean.RecordsBean> records = bean.getRecords();
                for (int j = 0; j < records.size(); j++) {
                    FindRecordBean.RecordsBean recordsBean = records.get(j);
                    if(  !recordsBean.isChecked())
                        continue;
                    int productId = recordsBean.getProductId();
                    if(i == data.size() -1 && j == records.size() - 1){
                        ids = ids + productId ;
                    }else{
                        ids = ids + productId + ",";
                    }

                }
            }

            //            http://47.114.162.17:9999/mall/shopsku/deleteRecords?ids=33

            String url = DataManager.BaseUrl + "mall/shopsku/deleteRecords?ids=" + ids;
            HashMap<String, String> headHashMap = new HashMap<>();
            headHashMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
            DataManager.toServer2(mContext, url, DataManager.GET_TYPE, "", headHashMap, new DataManager.GeResponse(){

                @Override
                public void onResponse(String response) {

                    try {
                        if(DataPares.isSucess(mContext,response)){
                            Toast.makeText(mContext, "删除成功", Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(mContext, "删除失败", Toast.LENGTH_SHORT).show();
                        }

                        initData();
                        System.out.println("");

                    }catch (Exception e){

                    }
                }
            });


        }catch (Exception e){

        }
    }



    public class Recode2Adapter extends RecyclerView.Adapter<Recode2Adapter.ViewHolder>{


        private ArrayList<FindRecordBean2> adapterList;

        public Recode2Adapter(ArrayList<FindRecordBean2> adapterList) {

            this.adapterList = adapterList;
        }

        public ArrayList<FindRecordBean2> getData(){
            return adapterList;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(parent.getContext()).
                    inflate(R.layout.recode_item2, null);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            inflate.setLayoutParams(layoutParams);
            return new Recode2Adapter.ViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            try {
                FindRecordBean2 bean = adapterList.get(position);
                holder.tv_time.setText(bean.getTime() + "");
                List<FindRecordBean.RecordsBean> records = bean.getRecords();

                RelativeLayout.LayoutParams params =new
                        RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);

                params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                holder.ll_content.removeAllViews();
                RelativeLayout rl = null;
                for (int i = 0; i < records.size(); i++) {
                    FindRecordBean.RecordsBean recordsBean = records.get(i);
                    if(i % 2 == 0){
                        rl = new RelativeLayout(mContext);
                        rl.addView(addList(recordsBean));
                        holder.ll_content.addView(rl);
                    }else{
                        rl.addView(addList(recordsBean),params);
                    }
                }
            }catch (Exception e){

            }


        }

        @Override
        public int getItemCount() {
            return adapterList.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            LinearLayout ll_content;
            TextView tv_time;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                ll_content = itemView.findViewById(R.id.ll_content);
                tv_time = itemView.findViewById(R.id.tv_time);
            }
        }
    }

    boolean isEdit = false;
    TextView rightText;
    Topview topview;
    private void initTop() {
//        StatusBarUtil.setColor(this,getResources().getColor(R.color.white_color) );
        StatusBarUtil.setTransparent(this);
//        StatusBarUtil.setTranslucent(this,250);

        topview = findViewById(R.id.topview);
        topview.setContentText("浏览记录");

        rightText = topview.getRightText();
        changeTopSatae();
        rightText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isEdit = !isEdit;
                changeTopSatae();
            }
        });
    }


    public void changeTopSatae(){
        if(isEdit){
            topview.setRightText("完成");
            rl_edit.setVisibility(View.VISIBLE);
            if(recode2Adapter != null)
            recode2Adapter.notifyDataSetChanged();
        }else{
            topview.setRightText("编辑");
            rl_edit.setVisibility(View.GONE);
            if(recode2Adapter != null)
            recode2Adapter.notifyDataSetChanged();
        }
    }

    public Product2SIngleView addList(FindRecordBean.RecordsBean recordsBean){
        Product2SIngleView product2SIngleView = new Product2SIngleView(mContext);
        product2SIngleView.setName(recordsBean.getShopProductInfoPojo().getProductName())
        .setDesc(recordsBean.getServiceCommitment())
        .setPrice(recordsBean.getPrice() + "")
        .setPicture(recordsBean.getShopProductPicturePojo().getAbbreviationPic())
        ;
        product2SIngleView.getCheckbox().setChecked(isAll);
        if(isEdit){
            product2SIngleView.getCheckbox().setVisibility(View.VISIBLE);
        }else{
            product2SIngleView.getCheckbox().setVisibility(View.GONE);
        }


        viewList.add(product2SIngleView);

        product2SIngleView.getCheckbox().setOnChangeLIstener(new OnChangeLIstener() {
            @Override
            public void onChangeLIstener() {
                boolean checked = product2SIngleView.getCheckbox().isChecked();
                recordsBean.setChecked(checked);
            }
        });
        return product2SIngleView;
    }

    private void initData() {
//        http://47.114.162.17:9999/mall/shopsku/findRecords?current=1&size=10
        String url = DataManager.BaseUrl + "mall/shopsku/findRecords?current=1&size=10";
        HashMap<String, String> headHashMap = new HashMap<>();
        headHashMap.put(DataManager.AuthorizationKey,DataManager.getToken(this));
        DataManager.toServer2(this, url, DataManager.GET_TYPE, "", headHashMap, new DataManager.GeResponse(){

            @Override
            public void onResponse(String response) {

                try {
                    System.out.println("");
                    FindRecordBean findRecordBean = JSON.parseObject(response, FindRecordBean.class);
                    List<FindRecordBean.RecordsBean> records = findRecordBean.getRecords();
                    detailData(records);
//                    timeList;

                    recode2Adapter = new Recode2Adapter(timeList);
                    refreshView.setAdapter(recode2Adapter);

                }catch (Exception e){

                }
            }
        });
    }
    ArrayList<FindRecordBean2> timeList = new ArrayList<>();
    private void detailData(List<FindRecordBean.RecordsBean> records) {

        try {
            timeList.clear();
           for (int i = 0; i < records.size(); i++) {
               FindRecordBean.RecordsBean recordsBean = records.get(i);
               String previewTime = recordsBean.getPreviewTime();
               if(TextUtils.isEmpty(previewTime))
                   continue;
               previewTime = previewTime.substring(0,10);
               List<FindRecordBean.RecordsBean> recordsBeans = timeIsContain(previewTime);
               if(recordsBeans == null){
                   FindRecordBean2 findRecordBean2 = new FindRecordBean2();
                   ArrayList<FindRecordBean.RecordsBean> cList = new ArrayList<>();
                   cList.add(recordsBean);
                   findRecordBean2.setRecords(cList);
                   findRecordBean2.setTime(previewTime);
                   timeList.add(findRecordBean2);
               }else{
                   recordsBeans.add(recordsBean);
               }
           }
       }catch (Exception e){

       }
    }

    public List<FindRecordBean.RecordsBean> timeIsContain(String previewTime){
         List<FindRecordBean.RecordsBean> list = null;
        try {
            for (int i = 0; i < timeList.size(); i++) {
                String time = timeList.get(i).getTime();
                if(time.equals(previewTime)){
                    list = timeList.get(i).getRecords();
                    return list;
                }
            }
        }catch (Exception e){

        }

        return list;
    }

}